package com.pkuse.bjousystem;

import com.pkuse.bjousystem.entity.school.School;
import com.pkuse.bjousystem.entity.school.ZwAuthEntity;
import com.pkuse.bjousystem.entity.student.Student;
import com.pkuse.bjousystem.repository.school.SchoolRepository;
import com.pkuse.bjousystem.repository.student.StudentRepository;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;


@Service
public class MyUserDetailsServiceImpl implements MyUserDetailsService {
    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private StudentRepository studentRepository;

    @Autowired
    private SchoolRepository schoolRepository;

    @Autowired
    private ZwAuthEntity zwAuthEntity;

    @Autowired
    private SchoolPasswordConfiguration schoolPasswordConfiguration;

    @Override
    public UserDetails loadEntityByIdAndType(String id, AuthEntity.AuthType authType) {
        logger.debug("当前id是:{}", id);
        switch (authType) {
            case Student:
                Student student = studentRepository.findById(id).orElseThrow(() -> new UsernameNotFoundException(id));
                logger.debug("查到{}为:{}", authType, student);
                return new MyUserPrincipal(student);
            case School:
                School school = schoolRepository.findById(id).orElseThrow(() -> new UsernameNotFoundException(id));
                logger.debug("查到{}为:{}", authType, school);
                return new MyUserPrincipal(new PasswordAuthEntity(school, schoolPasswordConfiguration));
            case Zw:
                if (zwAuthEntity.getAuthUsername().equals(id)) {
                    logger.debug("查到zw为:{}", zwAuthEntity);
                    return new MyUserPrincipal(new PasswordAuthEntity(zwAuthEntity, schoolPasswordConfiguration));
                } else {
                    throw new UsernameNotFoundException(id);
                }
            default:
                throw new UnsupportedEntityTypeException(authType.getType());
        }
    }
}
